//===----------------------------------------------------------------------===//
//
//                         BusTub
//
// seq_scan_executor.cpp
//
// Identification: src/execution/seq_scan_executor.cpp
//
// Copyright (c) 2015-2021, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "execution/executors/seq_scan_executor.h"

namespace bustub {

SeqScanExecutor::SeqScanExecutor(ExecutorContext *exec_ctx, const SeqScanPlanNode *plan)
: AbstractExecutor(exec_ctx) 
, plan_(plan)
{}

void SeqScanExecutor::Init() {  
    table_info_ = exec_ctx_->GetCatalog()->GetTable(plan_->GetTableOid()); // 从执行上下文中获取table_info
    table_begin_iter_ = table_info_->table_->Begin(exec_ctx_->GetTransaction());
    table_end_iter_ = table_info_->table_->End();
}

auto SeqScanExecutor::Next(Tuple *tuple, RID *rid) -> bool {   
    // if(table_begin_iter_ != table_end_iter_) {
    //     *tuple = *table_begin_iter_;
    //     *rid = tuple->GetRid();
    //     ++table_begin_iter_;
    //     return true;
    // }
    // return false;
    if (table_begin_iter_ == table_end_iter_) {
        return false;
    } 
    bool is_predicate = true;
    while (table_begin_iter_ != table_end_iter_) {
        // 如果需要筛选
        if (plan_->filter_predicate_ != nullptr) {
            is_predicate = plan_->filter_predicate_->Evaluate(&(*table_begin_iter_), plan_->OutputSchema()).CastAs(BOOLEAN).GetAs<bool>();
        }
        // 如果不需要筛选或者筛选成功
        if (is_predicate) {
            break;
        }
        ++table_begin_iter_;
    }
    // 没有符合筛选条件的tuple
    if (table_begin_iter_ == table_end_iter_) {
        return false;
    }
    *tuple = *table_begin_iter_;
    *rid = tuple->GetRid();
    return true;
}
    
}  // namespace bustub
